package com.trt.api.interceptors;

import com.trt.enums.ResponseStatusEnum;
import com.trt.exception.ApiException;
import com.trt.utils.IPUtil;
import com.trt.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author tanrentao
 * @date 2021-12-01
 * @desc 控制短信的拦截器： 拦截并限制60秒用户短信发送
 */
public class PassportInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtils redisUtils;

    public static final String MOBILE_SMSCODE = "mobile:smscode";

    /**
     * 拦截请求，访问controller之前
     *
     * @param request
     * @param response
     * @param handler
     * @return boolean
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取用户ip
        String userIP = IPUtil.getRequestIp(request);

        boolean keyIsExist = redisUtils.keyIsExist(MOBILE_SMSCODE + ":" + userIP);
        if (keyIsExist) {
            ApiException.display(ResponseStatusEnum.SMS_NEED_WAIT_ERROR);
            return false;
        }
        return false;
    }

    /**
     * 请求访问到controller之后，渲染视图之前
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 请求访问到controller之后，渲染视图之后
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
